package com.hospital.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.hospital.model.UserInfo;
import com.hospital.util.DbUtil;

public class UserInfoDAO {

	public UserInfo login(UserInfo user) {
		UserInfo userInfo = new UserInfo();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String sql = "select id, account, pswd, root, sex, birthday, address, tel, money,deptId,departmentName from t_user_info where account = ? and pswd = ? ";
		try {
			conn = DbUtil.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, user.getAccount());
			stmt.setString(2, user.getPswd());
			rs = stmt.executeQuery();
			if (rs.next()) {
				userInfo.setId(rs.getInt(1));
				userInfo.setAccount(rs.getString(2));
				userInfo.setPswd(rs.getString(3));
				userInfo.setRoot(rs.getString(4));
				userInfo.setSex(rs.getString(5));
				userInfo.setBirthday(rs.getString(6));
				userInfo.setAddress(rs.getString(7));
				userInfo.setTel(rs.getString(8));
				userInfo.setMoney(rs.getString(9));
				userInfo.setDeptId(rs.getString(10));
				userInfo.setDepartmentName(rs.getString(11));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(rs);
			DbUtil.close(stmt);
			DbUtil.close(conn);
		}
		return userInfo;
	}
	
	public boolean modifyPswd(UserInfo userInfo) {
		boolean flag = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = "update t_user_info set pswd = ? where id = ?";
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, userInfo.getPswd());
			pstmt.setInt(2, userInfo.getId());
			int t = pstmt.executeUpdate();
			if (t >= 1) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(pstmt);
			DbUtil.close(conn);
		}
		return flag;
	}

	public boolean accountIsExist(String account) {
		boolean flag = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from t_user_info where account = ?";
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, account);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(rs);
			DbUtil.close(pstmt);
			DbUtil.close(conn);
		}
		return flag;
	}
}
